package com.zhc.community.service;


import com.zhc.community.dao.DiscussPostMapper;
import com.zhc.community.entity.DiscussPost;
import com.zhc.community.util.SensitiveFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.IllformedLocaleException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class DiscussPostService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

    @Resource
    private DiscussPostMapper discussPostMapper;

    @Resource
    private SensitiveFilter sensitiveFilter;

//    @Value("${caffeine.posts.max-size}")
//    private int maxSize;
//
//    @Value("{$caffeine.post.expire-seconds}")
//    private int expireSeconds;
//
//    // Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache
//
//    // 帖子列表缓存
//    private LoadingCache<String, List<DiscussPost>> postListCache;
//
//    // 帖子总数缓存
//    private LoadingCache<Integer, Integer> postRowsCache;

//    @PostConstruct
//    public void init() {
//        // 初始化帖子列表缓存
//        postListCache = Caffeine.newBuilder()
//                .maximumSize(maxSize)
//                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
//                .build(new CacheLoader<String, List<DiscussPost>>() {
//                    @Nullable
//                    @Override
//                    public List<DiscussPost> load(@NonNull String key) throws Exception {
//                        if (key == null || key.length() == 0) {
//                            throw new IllegalArgumentException("参数错误!");
//                        }
//
//                        String[] params = key.split(":");
//                        if (params == null || params.length != 2) {
//                            throw new IllegalArgumentException("参数错误!");
//                        }
//
//                        int offset = Integer.valueOf(params[0]);
//                        int limit = Integer.valueOf(params[1]);
//
//                        // 二级缓存: Redis -> mysql
//
//                        logger.debug("load post list from DB.");
//                        return discussPostMapper.selectDiscussPost(0, offset, limit, 1);
//                    }
//                });
//        // 初始化帖子总数缓存
//        postRowsCache = Caffeine.newBuilder()
//                .maximumSize(maxSize)
//                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
//                .build(new CacheLoader<Integer, Integer>() {
//                    @Nullable
//                    @Override
//                    public Integer load(@NonNull Integer key) throws Exception {
//                        logger.debug("load post rows from DB.");
//                        return discussPostMapper.selectDiscussPostRows(key);
//                    }
//                });
//    }

    //当传入userId时就查询该id的帖子，不传userId时就查询全部帖子，实现动态SQL
    public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit, int orderMode) {
        return discussPostMapper.selectDiscussPost(userId, offset, limit, orderMode);
    }


    //查看我的帖子
    public List<DiscussPost> findmyDiscussPosts(int userId, int offset, int limit) {
        return discussPostMapper.findmyDiscussPosts(userId, offset, limit);
    }


    //查询帖子行数
    public int findDiscussPostRows(int userId) {
        return discussPostMapper.selectDiscussPostRows(userId);
    }

    //插入帖子
    public int addDiscussPost(DiscussPost post){
        if (post == null){
            throw new IllegalArgumentException("参数不能为空");
        }

        //转义HTML标签
        post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
        post.setContent(HtmlUtils.htmlEscape(post.getContent()));

        //过滤敏感词
        post.setTitle(sensitiveFilter.filter(post.getTitle()));
        post.setContent(sensitiveFilter.filter(post.getContent()));

        return discussPostMapper.insertDiscussPost(post);
    }

    //帖子详情
    public DiscussPost findDiscussPostById(int id){
        return discussPostMapper.selectDiscussPostById(id);
    }

    //更新帖子的评论数量
    public int updateCommentCount(int id, int commentCount){
        return discussPostMapper.updateCommentCount(id,commentCount);
    }

    //
    public int updateType(int id, int type){
        return discussPostMapper.updateType(id,type);
    }

    public int updateStatus(int id, int status){
        return discussPostMapper.updateStatus(id,status);
    }

    public int updateScore(int id, double score){
        return discussPostMapper.updateScore(id,score);
    }


}
